﻿using System.Collections.Generic;
using System.Linq;
using HappyBa.Core.Data;
using Mnk.Library.Common.Models;

namespace HappyBa.Pages
{
    class NodeEntityAdapter : IHasChildren
    {
        public UIEntityBase Entity { get; private set; }
        public NodeEntityAdapter(UIEntityBase entity)
        {
            Entity = entity;
        }

        public IList<IHasChildren> Children
        {
            get
            {
                var r = Entity as UIProject;
                if (r != null)
                    return r.Bugs.Cast<UIEntityBase>()
                            .Concat(r.UserStories)
                            .Select(x => new NodeEntityAdapter(x))
                            .Cast<IHasChildren>()
                            .ToArray();
                var us = Entity as UIUserStory;
                if (us != null)
                    return us.Impediments.Cast<UIEntityBase>()
                            .Concat(us.Bugs)
                            .Concat(us.Tasks)
                            .Select(x => new NodeEntityAdapter(x))
                            .Cast<IHasChildren>()
                            .ToArray();
                var task = Entity as UITask;
                if (task != null)
                {
                    return task.Impediments.Cast<UIEntityBase>()
                            .Select(x => new NodeEntityAdapter(x))
                            .Cast<IHasChildren>()
                            .ToArray();
                }
                var bug = Entity as UIBug;
                if (bug != null)
                {
                    return bug.Impediments.Cast<UIEntityBase>()
                            .Select(x => new NodeEntityAdapter(x))
                            .Cast<IHasChildren>()
                            .ToArray();
                }
                return new IHasChildren[0];
            }
        }

        public override string ToString()
        {
            return string.Format("{0}:{1} {2}", Entity.EntityType.Name, Entity.Id, Entity.Name);
        }
    }
}

